package hxg.thread;

import java.util.concurrent.*;

/**
 * @author HeXiangGuang
 * @create 2021-06-23 22:47
 */
public class Demo4 {
    public static void main(String[] args) {
        //1创建线程池
        ExecutorService es = Executors.newFixedThreadPool(2);
        //2.提交任务Future:表示要执行的任务结果
        Future<Integer> future1 = es.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println(Thread.currentThread().getName() + "开始计算！");
                int sum = 0;
                for (int i = 1; i <= 50; i++) {
                    sum += i;
                }
                System.out.println(Thread.currentThread().getName() + "0-50计算完毕");
                return sum;
            }
        });
        
        Future<Integer> future2 = es.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 51; i <= 100; i++) {
                    sum += i;
                }
                System.out.println(Thread.currentThread().getName() + "51-100计算完毕");
                return sum;
            }
        });
        //3获取任务结果
        Integer sum = null;
        try {
            sum = future1.get() + future2.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(sum);
        //4关闭线程池
        es.shutdown();
    }
}
